<template>
  <vxe-grid
    ref="xGrid"
    class="gridsortable"
    v-bind="gridOptions"
    stripe
    round
    v-on="gridEvents"
    :header-cell-class-name="gridOptions.headerCellClassName"
    :row-class-name="gridOptions.rowClassName"
    :cell-class-name="gridOptions.cellClassName"
    @checkbox-change="setSelected"
    @checkbox-all="selectAllEvent"
  >
    <template #time-line>
      <slot name="time-line"></slot>
    </template>

    <template #tools>
      <slot name="toolbar_right">
        <skFilterBar
          v-if="gridOptions.toolbarConfig.search"
          filterName="filterName"
          :options="gridOptions"
          @filterChange="scFilterBarchange"
          :xGrid="xGrid"
          ref="skFilterRef"
          style="margin-right: 12px"
        >
          <template #default="{ filterLength, openFilter }">
            <el-badge :value="filterLength" type="danger" :hidden="filterLength <= 0">
              <vxe-button
                class="el-icon vxe-button type--button size--mini is--circle"
                icon="vxe-icon-search"
                @click="openFilter"
              ></vxe-button>
            </el-badge>
          </template>
        </skFilterBar>
        <vxe-button
          v-if="gridOptions.toolbarConfig.setting"
          class="el-icon vxe-button type--button size--mini is--circle"
          style="margin-right: 12px"
          @click="openSaveDialogConfig"
        >
          <el-icon size="14">
            <ElIconSetting />
          </el-icon>
        </vxe-button>
        <vxe-button
          v-if="gridOptions.toolbarConfig.reload"
          class="el-icon vxe-button type--button size--mini is--circle"
          style="margin-right: 12px"
          @click="reload"
        >
          <el-icon size="14">
            <ElIconRefresh />
          </el-icon>
        </vxe-button>
      </slot>
    </template>

    <template #btns>
      <vxe-button type="submit" content="查询"></vxe-button>
      <vxe-button
        type="reset"
        @click="gridEvents.filterReset"
        content="重置"
      ></vxe-button>
    </template>
  </vxe-grid>
  <contextMenu ref="contextM" :menu="menuList" :grid="xGrid" :gridEvents="gridEvents">
  </contextMenu>

  <save-config
    v-if="dialogConfigShow"
    ref="saveDialogConfig"
    @success="SaveConfighandleSuccess"
    @closed="dialogConfigShow = false"
  ></save-config>
  <imports
    v-if="importsDlg"
    ref="importsDlgConfig"
    @success="refresh"
    @closed="importsDlg = false"
  ></imports>
</template>

<script>
import {
  defineComponent,
  onMounted,
  reactive,
  ref,
  watch,
  onUnmounted,
  nextTick,
  onActivated,
  onDeactivated,
} from "vue";
import { ElMessageBox, ElNotification } from "element-plus";
import { useRouter } from "vue-router";
import { VXETable } from "vxe-table";
import XEUtils from "xe-utils";
import imports from "./import";
import skFilterBar from "@/components/skFilterBar";
import contextMenu from "@/components/skContextMenu";
import "./plugins/formatter.js";
import "./plugins/table/index.js";
import api from "./../../api";
import { http } from "@/utils/request";
import tool from "@/utils/tool";
import Sortable from "sortablejs";
import saveConfig from "@/views/setting/tableconfig/save";
// import "./plugins/index.ts"
VXETable.setConfig({
  size: "mini",
});

// VXETable.interceptor.add("event.reset", () => {
//   // 比如点击了某个组件的弹出层面板之后，此时被激活单元格不应该被自动关闭，通过返回 false 可以阻止默认的行为。
//   alert(1);
//   return false;
// });
export default defineComponent({
  components: { skFilterBar, saveConfig, contextMenu, imports },
  props: {
    gridOps: {
      type: Object,
      default: () => {
        return { tablecode: null };
      },
    },
    gridEvts: {},
    url: { type: Object, default: () => null },
    fieldUrl: { type: Object, default: () => null },
    tablecode: {
      type: String,
      default: () => "",
    },
    children: { type: Object, default: () => null },
    checkMethod: null,
    params: null,
    sortable: { type: Boolean, default: () => false },
    data: { type: Array, default: () => null },
    height: { type: [String, Number], default: () => "auto" },
    sort: { type: String, default: () => null },
    order: { type: String, default: () => null },
  },
  emits: [
    "headerCellClick",
    "filterReset",
    "headerCellDblclick",
    "headerCellMenu",
    "cellClick",
    "cellDblclick",
    "cellMenu",
    "footerCellClick",
    "footerCellDblclick",
    "footerCellMenu",
    "checkboxChange",
    "checkboxAll",
    "selectData",
    "scroll",
    "zoom",
    "toolbarButtonClick",
    "beforeEditMethod",
    "editClosed",
    "reload",
    "refresh",
  ],
  setup(props, content) {
    const emit = content.emit;
    const xGrid = ref({});
    const queryParams = {};
    const router = useRouter();
    const serveApiUrl = ref(props.url?.cp());
    let filterBarData = [];
    let searchData = [];
    let filterAll = [];
    const footerData = ref(null);
    const importsDlg = ref({});
    const importsDlgConfig = ref({});
    const menuList = ref([]); //右键菜单
    const contextM = ref();
    const skFilterRef = ref({});
    const selectRecords = ref([]); //选择项
    const gridOptions = reactive({
      data: props.data,
      height: props.height,
    });
    watch(
      () => props.url,
      () => {
        if (props.url.url != serveApiUrl.value.url) {
          serveApiUrl.value = props.url.cp();
          refresh();
        }
      }
    );
    watch(
      () => props.data,
      () => {
        gridOptions.data = props.data;
      }
    );
    watch(
      () => props.height,
      () => {
        gridOptions.height = props.height;
      }
    );
    const fieldUrl = api.system.table.info;

    let proxyConfig = {
      seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
      sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
      filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
      form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
      message: false,
      // 对应响应结果 { result: [], page: { total: 100 } }
      props: {
        result: "rows", // 配置响应结果列表字段
        total: "total", // 配置响应结果总页数字段
      },
      afterQuery: () => {
        nextTick(() => {
          if (gridOptions.tree && gridOptions.treeConfig.expandAll)
            xGrid.value.setAllTreeExpand(true);
        });
      },
      // 只接收Promise，具体实现自由发挥
      ajax: {
        // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
        query: ({ page, sorts, filters, form, $grid }) => {
          const firstSort = sorts[0];

          if (firstSort) {
            if (
              firstSort.column.filterRender &&
              firstSort.column.filterRender != "" &&
              firstSort.column.filterRender.attrs.filterfield != firstSort.property &&
              firstSort.column.filterRender.attrs.filterfield != null
            ) {
              queryParams.sort = firstSort.column.filterRender.attrs.filterfield;
            } else queryParams.sort = firstSort.property;
            queryParams.order = firstSort.order;
          } else if (props.sort) {
            queryParams.sort = props.sort;
            queryParams.order = props.order;
          }
          queryParams["filter"] = [];
          let formfilter = tool.removeNull(form);

          gridOptions.formConfig.items.filter(filter => {
            if (formfilter[filter.field] == null && filter.defaultvalue) {
              formfilter[filter.field] = filter.defaultvalue;
            }
          });
          if (Object.keys(formfilter).length > 0) queryParams["filter"].push(formfilter);
          // 处理筛选条件
          filters.forEach(data => {
            let filter = data.datas[0];
            let field = "";
            //select 筛选 值和内容可能不一样
            if (filter.filterfield != null && filter.filterfield != "")
              field = filter.filterfield;
            else field = data.property;
            if (typeof filter.value == "string")
              if (filter.value.substring(0, 1) == "{") {
                filter = JSON.parse(filter.value.replace(/'/g, '"'));
              }
            queryParams["filter"].push({ [field]: filter });
          });

          filterBarData.forEach(data => {
            queryParams["filter"].push(data);
          });

          searchData.forEach(data => {
            queryParams["filter"].push(data);
          });
          if (props.params != null) {
            //是函数，就取返回值
            let prop_params =
              props.params instanceof Function ? props.params() : props.params;
            //不是数组，就转数组
            prop_params = prop_params instanceof Array ? prop_params : [prop_params];
            //循环添加筛选条件
            prop_params.map(param => {
              queryParams["filter"].push(param);
            });
          }
          filterAll = queryParams;
          queryParams["page"] = page.currentPage;
          queryParams["pageSize"] = page.pageSize;
          let sumparam = [];

          Object.values($grid.props.columns).forEach(function (k) {
            if (k.sum) {
              sumparam[sumparam.length] = k.field;
            }
          });

          if (gridOptions.footerRowCount == 2) {
            if (sumparam.length > 0) queryParams["sums"] = sumparam;
          }
          if (gridOptions.just_fetch_field)
            queryParams["table_id"] = gridOptions.table_id;
          return serveApiUrl.value
            .post(queryParams)
            .then(function (res) {
              $grid.footsum = res.data.sums;
              footerData.value = res.data.footer ?? null;
              return {
                rows: res.data.rows ?? res.data,
                total: res.data.total ?? 0,
                data: res.data,
              };
            })
            .then(v => {
              gridEvents.afterQuery(v);
              return v;
            });
        },

        // 当点击工具栏删除按钮或者手动提交指令 delete 时会被触发
        delete: async ({ body }) => {
          const type = await ElMessageBox.confirm("您确定要删除该数据?");
          if (type === "confirm") {
            return http
              .post(`${serveApiUrl.value.url}/../delete`, body)
              .then(res => {
                if (res.code == "200")
                  ElNotification({
                    title: "删除成功",
                    message: "删除成功",
                    type: "success",
                  });
              })
              .finally(() => closeLoading());
          }
        },
        // 当点击工具栏保存按钮或者手动提交指令 save 时会被触发
        save: ({ body }) => {
          return gridEvents.saveRow(body);
        },
      },
    };
    if (serveApiUrl.value == null) {
      proxyConfig = null;
    }

    const saveDialogConfig = ref({});
    const dialogConfigShow = ref(false);
    let TableDefaultData = null;
    const SaveConfighandleSuccess = function () {
      (props.fieldUrl ?? fieldUrl).destroycache({
        code: props.tablecode,
      });
      reloadConfig();
    };
    const openSaveDialogConfig = function () {
      dialogConfigShow.value = true;
      nextTick(() => {
        saveDialogConfig.value.open("edit").setData(TableDefaultData);
      });
    };

    const gridEvents = {
      headerCellClick(data) {
        emit("headerCellClick", data);
      },

      filterReset() {
        //清空数据
        gridOptions.toolbarConfig.search && skFilterRef.value.clear();
      },
      refresh() {
        emit("refresh");
      },
      reload() {
        emit("reload");
      },
      headerCellDblclick(data) {
        emit("headerCellDblclick", data);
      },
      headerCellMenu(data) {
        emit("headerCellMenu", data);
      },
      beforeEditMethod(data) {
        emit("beforeEditMethod", data);
        return true;
      },
      editClosed(data) {
        emit("editClosed", data);
      },
      cellClick(data) {
        if (data.column.type != "checkbox") {
          if (props.checkMethod && !props.checkMethod(data)) {
            return data.$table.setCheckboxRow([data.row], false);
          }
          //没有按ctrl，就清空选择，变单选
          if (!data.$event.ctrlKey) data.$table.clearCheckboxRow();

          data.$table.setCheckboxRow(
            [data.row],
            !data.$table.isCheckedByCheckboxRow(data.row)
          );
          setSelected();
        }

        emit("cellClick", data);
      },
      cellDblclick(data) {
        emit("cellDblclick", data);
      },
      afterQuery() {},
      cellMenu(data) {
        if (menuList.value.length > 0) contextM.value.handleContextMenu(data.$event);
        emit("cellMenu", data);
      },
      footerCellClick(data) {
        emit("footerCellClick", data);
      },
      footerCellDblclick(data) {
        emit("footerCellDblclick", data);
      },
      footerCellMenu(data) {
        emit("footerCellMenu", data);
      },
      checkboxChange(data) {
        emit("checkboxChange", data);
      },
      checkboxAll(data) {
        gridEvents.checkboxChange(data);
        emit("checkboxAll", data);
      },
      //返回上一个结果集的交集，差集
      selectData(data) {
        emit("selectData", data);
      },
      scroll(data) {
        emit("scroll", data);
      },
      zoom(data) {
        emit("zoom", data);
      },
      selectColor: function (color, row) {
        http.post(`${serveApiUrl.value.url}/../setRowColor`, {
          id: row.id,
          color: color,
        });
      },
      toolbarButtonClick: function (param) {
        //按钮执行函数
        emit("toolbarButtonClick", param);

        let promise = new Promise(() => {});
        if (typeof gridEvents[param.code] == "function") {
          let resdata = gridEvents[param.code](param);
          if (typeof resdata === "object" && typeof resdata.then === "function") {
            showLoading();
            promise = resdata;
          }
        } else if (
          mergeOptions.proxyConfig &&
          typeof mergeOptions.proxyConfig.ajax[param.code] == "undefined"
        ) {
          showLoading();
          promise = http.post(`${serveApiUrl.value.url}/../` + param.code, {
            ids: param.button.selectRecords.map(
              el => el[mergeOptions.rowConfig.keyField ?? "id"]
            ),
          });
        } else {
          promise = new Promise(() => {});
        }
        return promise
          .then(data => {
            if ((data?.code ?? "") == "200") {
              ElNotification({
                title: "操作成功！",
                message: data.message,
                type: "success",
              });
              // 刷新表格
              refresh();
            }
          })
          .finally(() => closeLoading());
      },
      imports: () => {
        importsDlg.value = true;
        nextTick(() => {
          importsDlgConfig.value.setData(
            gridOptions.excelurl,
            `${serveApiUrl.value.url}/../import`
          );
          importsDlgConfig.value.open();
        });
      },
      printReport: param => {
        const url = router.resolve({
          name: "printReport",
        });
        let dataUrl =
          `${serveApiUrl.value.url}/../` + //页面数据地址
          "printReport?name=" + //换个方法
          param.button.name;
        let endUrl =
          `${serveApiUrl.value.url}/../` + //页面数据地址
          "OnPrintEnd?name=" + //换个方法
          param.button.name;

        param.button.selectRecords.filter(el => {
          dataUrl += "&ids[]=" + el[mergeOptions.rowConfig.keyField ?? "id"];
          endUrl += "&ids[]=" + el[mergeOptions.rowConfig.keyField ?? "id"];
        });

        tool.data.set("printReport", {
          grf: param.button.url,
          url: dataUrl,
          endUrl: endUrl,
          queryParams: queryParams,
        });
        window.open(url.href, "_blank");
      },
      editRow: param => {
        let Records = param.$grid.getCheckboxRecords();
        for (let i in Records) param.$grid.setEditRow(Records[i]);
      },
      afterAddRow: () => {},
      beforeAddRow: () => {},
      saveRow: body => {
        return http.post(`${serveApiUrl.value.url}/../save`, body);
      },
      //重新新增一行方法
      addRow: param => {
        var clm = {};

        gridOptions.columns.forEach(v => {
          if (v.field != "id") {
            XEUtils.set(clm, v.field, v.defaultValue ?? v.editValue);
          }
        });
        if (gridEvents.beforeAddRow(clm, param) === false) return;
        gridOptions.data.push(clm);
        param.$grid.setEditRow(clm);
        gridEvents.afterAddRow(clm, param);
      },
      removeRow: async () => {
        ElMessageBox.confirm("您确定要删除该数据?")
          .then(type => {
            if (type === "confirm") {
              let count = 0;
              let defaultData = gridOptions.data.concat([]);
              defaultData.filter((item, index) => {
                selectRecords.value.some(v => v == item) &&
                  gridOptions.data.splice(index - count++, 1);
              });
            }
          })
          .catch(() => {});
      },
    };

    //查询后保存参数

    const mergeOptions = {
      border: true,
      showFooter: false,
      tablecode: "",
      showOverflow: true,
      just_fetch_field: false,
      loading: false,
      mouseConfig: {
        selected: true,
      },
      //会把初始化数据清空了
      menuConfig: {},
      footerMethod: function (dataGrid) {
        var footer1 = [];
        var footer2 = [];
        var hasfoot2 = true;
        var digits = 2;
        var hideCount = 0;
        if (
          typeof dataGrid.$grid.footsum == "undefined" ||
          (footerData.value && footerData.value[1] === undefined)
        )
          hasfoot2 = false;
        for (var col in dataGrid.$grid.props.columns) {
          //隐藏的列数
          var row = dataGrid.$grid.props.columns[col];
          if (row.visible === false) {
            hideCount++;
            continue;
          }
          if (row.sum != true) {
            continue;
          }
          footer1[col - hideCount] = footerData.value
            ? footerData.value[0] === undefined
              ? ""
              : footerData.value[0][row.field]
            : XEUtils.toFixed(XEUtils.sum(dataGrid.data, row.field), digits);
          if (hasfoot2)
            footer2[col - hideCount] = footerData.value
              ? footerData.value[1] === undefined
                ? ""
                : footerData.value[1][row.field]
              : XEUtils.toFixed(
                  XEUtils.toNumber(dataGrid.$grid.footsum[row.field]),
                  digits
                );
        }
        if (!hasfoot2) return [footer1];
        else return [footer1, footer2];
      },

      keepSource: true,
      id: "full_edit_1",
      rowConfig: {
        keyField: "id",
        isHover: true,
        height: 30,
        useKey: "id",
      },
      columnConfig: {
        resizable: true,
        useKey: "id",
      },

      printConfig: {
        columns: [
          { field: "name" },
          { field: "email" },
          { field: "nickname" },
          { field: "age" },
          { field: "amount" },
        ],
      },
      sortConfig: {
        trigger: "cell",
        remote: true,
      },
      filterConfig: {
        remote: true,
      },

      vtoolbarConfig: {
        slots: {
          tools: "tools",
        },
        zoom: true,
        refresh: true,
        import: false,
        print: true,
        custom: true,
        export: true,
      },
      proxyConfig: proxyConfig,

      importConfig: {
        remote: false,
        types: ["xlsx"],
        modes: ["insert"],
        // 自定义服务端导入
        importMethod({ file }) {
          const formBody = new FormData();
          formBody.append("file", file);
          return http
            .post(`${serveApiUrl.value.url}/../import`, formBody)
            .then(response => response.json())
            .then(data => {
              ElNotification({
                title: "操作成功",
                message: `成功导入 ${data.result.insertRows} 条记录！`,
                type: "success",
              });
              // 导入完成，刷新表格
              refresh();
            })
            .finally(() => closeLoading());
        },
      },
      exportConfig: {
        remote: true,
        types: ["xlsx", "csv"],
        modes: ["current", "selected", "all"],
        isFooter: false,
        columnFilterMethod({ column }) {
          if (typeof column.field == "undefined" || column.visible == false) return false;
          return true;
        },
        // columns: [],
        // async beforeExportMethod({ options }) {

        // },
        // 自定义服务端导出
        exportMethod({ options }) {
          const $grid = xGrid.value;
          showLoading();
          if (options.mode == "all") {
            filterAll.pageSize = 99999999;
            filterAll.page = 1;
            filterAll.table_id = gridOptions.table_id;
            serveApiUrl.value.get(filterAll).then(res => {
              closeLoading();
              options.data = res.data.rows;
              options.remote = false;
              $grid.exportData(options);
            });
          } else {
            options.remote = false;
            $grid.exportData(options);
          }
        },
      },
      checkboxConfig: {
        // labelField: "id",

        highlight: true,
        //父子不关联，树
        checkStrictly: false,
        trigger: "cell",

        //保留勾选
        reserve: true,
        //通过鼠标在复选框的列内滑动选中或取消指定行
        visibleMethod: props.visibleMethod,
        checkMethod: props.checkMethod,
      },

      editConfig: {
        trigger: "click",
        mode: "row",
        autoClear: false, //设置为true的话，点击任意位置，会清空编辑状态，导致弹窗编辑页面 直接消失
        showIcon: false,
        showStatus: false,
        beforeEditMethod: data => gridEvents.beforeEditMethod(data),
      },
      set toolbarConfig(val) {
        let assignSelectBtnsRecords = buttons => {
          return buttons.map(btn => {
            btn.selectRecords = selectRecords;
            if (btn.children?.length > 0) {
              btn.children = assignSelectBtnsRecords(btn.children);
            }
            return btn;
          });
        };

        //保存选择项
        if (val.buttons) {
          val.buttons.map(v => {
            v.buttonRender.button.selectRecords = selectRecords;
            v.buttonRender.button.gridEvents = gridEvents;
            if ([1, 3].includes(v.buttonRender.button.type_id))
              v.buttonRender.button.show = true;
            if ([2, 3].includes(v.buttonRender.button.type_id)) {
              assignSelectBtnsRecords(v.buttonRender.button.children);
              menuList.value.push(v.buttonRender.button);
            }
            return v;
          });
        }
        if (this.vtoolbarConfig) {
          Object.assign(this.vtoolbarConfig, val);
        } else {
          this.vtoolbarConfig = val;
        }
      },
      get toolbarConfig() {
        return this.vtoolbarConfig;
      },

      set columns(val) {
        val.forEach((v, k) => {
          if (["seq", "checkbox", "radio", "expand"].indexOf(v.type) === -1) {
            if (v.filterable == true) {
              v["xtype"] = v.type == "html" ? "text" : v.type;
              v["filters"] = [
                {
                  data: {
                    type: v.type == "number" ? "eq" : "lk",
                    xtype: v.type == "html" ? "text" : v.type,
                    value: v.editValue ?? "", //筛选默认值
                    filterfield: v.filterfield,
                  },
                  checked: (v.editValue ?? "") !== "", //启动筛选
                },
              ];
              val[k]["filterRender"] = {
                name: "FilterNew",
                attrs: v,
              };
            }
            if (v.editable == true && v.type != "CellRender") {
              v["xtype"] = v.type;
              val[k]["editRender"] = {
                name: "EditRender",
                attrs: v,
                autofocus: "input",
              };
            }
            if (v.type == "CellRender") {
              val[k]["cellRender"] = {
                name: v.formatter,
                attrs: v,
              };
              delete val[k].formatter;
            }
            if (v.type == "ColorRender") {
              val[k]["cellRender"] = {
                name: "colorRender",
                attrs: v,
                gridEvents: gridEvents,
              };
              delete val[k].formatter;
            }
          }
        });

        if (this.vcolumns) {
          val.forEach(v => {
            this.vcolumns.some((vv, kk) => {
              if (v.field == vv.field) {
                if (vv.editRender == true && typeof v.event != "undefined") {
                  this.vcolumns[kk]["EditRender"]["event"] = v.event;
                }
                Object.assign(this.vcolumns[kk], v);
                return true;
              }
            });
          });
        } else {
          this.vcolumns = val;
        }
      },
      get columns() {
        return [
          { visible: false },
          { visible: false },
          { visible: false },
          { visible: false },
          ...this.vcolumns,
        ];
      },
    };
    const reloadConfig = async (gridOps = [], event = []) => {
      Object.assign(
        mergeOptions,
        await getRemoteOption(
          props.fieldUrl ?? fieldUrl,
          props.gridOps.tablecode ?? props.tablecode
        ),
        props.gridOps
      );
      Object.assign(gridOptions, mergeOptions, gridOps);

      Object.assign(gridEvents, props.gridEvts, event);

      gridOptions.formConfig.items = gridOptions.formConfig.items.map(filter => {
        if (
          ["monthRange", "daterange", "datetimerange"].indexOf(filter.type) &&
          filter.defaultvalue
        ) {
          if (tool[filter.defaultvalue])
            filter.itemRender.defaultvalue = filter.defaultvalue = tool[
              filter.defaultvalue
            ]();
        }
        return filter;
      });

      //树形
      if (props.sortable) {
        gridOptions.editConfig["trigger"] = "dblclick";

        // 加载完成之后在绑定拖动事件
        rowDrop();
      }

      let seqWith = 35;

      if (gridOptions.tree) {
        let hasSetTree = false;
        gridOptions.checkboxConfig.checkStrictly = true;
        if (gridOptions.treeConfig["expandField"]) {
          gridOptions.columns.filter((item, k) => {
            if (gridOptions.treeConfig["expandField"] == item.field) {
              gridOptions.columns[k]["treeNode"] = hasSetTree = true;
              gridOptions.columns[k]["align"] = "left";
            }
          });
        }
        if (!hasSetTree)
          gridOptions.columns[3] = {
            width: 30,
            align: "center",
            treeNode: gridOptions.tree,
          };
      }
      if (props.children != null) {
        gridOptions.columns[2] = {
          type: "expand",
          width: 35,
          align: "center",
          contentRender: {
            name: "childrenTableRender",
            attrs: props.children,
          },
        };
      }
      if (gridOptions.showCheckBox) {
        gridOptions.columns[1] = {
          type: "checkbox",
          width: 35,
          align: "center",
          fixed: "left",
        };
      }

      // else delete gridOptions.columns[1];
      if (gridOptions.showColumnNum & !props.sortable)
        gridOptions.columns[0] = {
          type: "seq",
          width: seqWith,
          fixed: "left",
        };
      if (props.sortable) {
        gridOptions.columns[0] = {
          width: 30,
          align: "center",
          cellRender: { name: "dragRender" },
        };
      }
    };
    onMounted(async () => {
      await reloadConfig();
    });
    //设置筛选
    function scFilterBarchange(data) {
      filterBarData = data;
      refresh();
    }

    //简单的包含搜索
    function search(field, value, type) {
      searchData.forEach(function (v, k) {
        if (typeof v[field] != "undefined") delete searchData[k];
      });
      searchData[searchData.length] = {
        [field]: { value: value, type: type },
      };
    }
    const getRemoteOption = async (url, param) =>
      await url.get({ code: param }).then(v =>
        Object.assign({}, (TableDefaultData = v.data), {
          id: v.data.code,
          table_id: v.data.id,
        })
      );

    const setSelected = () => {
      //返回的是老数据
      selectRecords.value = xGrid.value.getCheckboxRecords();
    };

    const selectAllEvent = () => setSelected();

    const showLoading = () => {
      gridOptions.loading = true;
    };
    const closeLoading = () => {
      gridOptions.loading = false;
    };

    let sortable1;
    const rowDrop = () => {
      nextTick(() => {
        const $table = xGrid.value;
        sortable1 = Sortable.create(
          $table.$el.querySelector(".body--wrapper>.vxe-table--body tbody"),
          {
            handle: ".drag-btn",
            animation: 150,
            onEnd: sortableEvent => {
              const newIndex = sortableEvent.newIndex;
              const oldIndex = sortableEvent.oldIndex;

              if (gridOptions.data) {
                const currRow = gridOptions.data.splice(oldIndex, 1)[0];
                gridOptions.data.splice(newIndex, 0, currRow);
              } else {
                const data = $table.getTableData().tableData;
                const currRow = data.splice(oldIndex, 1)[0];
                data.splice(newIndex, 0, currRow);
                //先清空在加载
                $table.loadData([]).then(() => {
                  $table.loadData(data);
                });
              }
            },
          }
        );
      });
    };

    onUnmounted(() => {
      if (props.sortable) {
        if (sortable1) {
          sortable1.destroy();
        }
      }
    });
    const reload = () => {
      return xGrid.value.commitProxy("query").then(res => {
        setSelected();
        gridEvents.reload(res);
      });
    };
    const refresh = () => {
      return xGrid.value.commitProxy("query").then(res => {
        setSelected();
        gridEvents.refresh(res);
      });
    };
    let isreactive = false;
    onActivated(() => {
      isreactive && refresh();
      isreactive = false;
    });
    onDeactivated(() => {
      isreactive = true;
    });
    const getSelectRecords = () => {
      return selectRecords.value;
    };
    return {
      xGrid,
      refresh,
      reload,
      saveDialogConfig,
      dialogConfigShow,
      SaveConfighandleSuccess,
      openSaveDialogConfig,
      gridOptions,
      gridEvents,
      scFilterBarchange,
      skFilterRef,
      search,
      setSelected,
      selectAllEvent,
      menuList,
      contextM,
      importsDlg,
      importsDlgConfig,
      closeLoading,
      getSelectRecords,
    };
  },
});
</script>

<style>
.vxe-export--panel tbody tr:last-of-type {
  display: none;
}

.vxe-export--panel-column-body li:nth-child(-n + 3) {
  display: none;
}

.gridsortable .drag-btn {
  cursor: move;
  font-size: 12px;
}

.gridsortable .vxe-body--row.sortable-ghost,
.gridsortable .vxe-body--row.sortable-chosen {
  background-color: #dfecfb;
}

/* .table-grid {
  height: calc(100% - 2px);
} */

.table-grid .vxe-table--footer-wrapper.body--wrapper {
  overflow-x: hidden;
}
</style>
